﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Sendz.Validators
{
    // Always validate fields with _email in their name
    // Need to register this in global.asax.cs for this to work as: ModelValidatorProviders.Providers.Add(new CustomMetadataValidationProvider()); 
    // Ref: http://stackoverflow.com/questions/3607247/dataannotations-dynamically-attaching-attributes/3609521#3609521
    public class CustomMetadataValidationProvider : DataAnnotationsModelValidatorProvider
    {
        protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes)
        {
            if (!string.IsNullOrWhiteSpace(metadata.PropertyName) && metadata.PropertyName.ToLowerInvariant().IndexOf("email") > -1)
                attributes = new List<Attribute>() { new RegularExpressionAttribute(@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$") };

            return base.GetValidators(metadata, context, attributes);
        }
    }
}
